import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Icon, Modal, Form, Input, Select, Upload, Button, Tag ,message} from 'antd';
//@ts-ignore
import LzEditor from 'react-lz-editor';
import Service from '@/public/http/services';
import { mapToArray } from '@/public/utils/index';
import { GoodsType, FictitiousGoodsType } from '@/public/constant/enums';
import Sku from './Sku';
import style from './index.css';
const { Option } = Select;
const CreateModal: React.FC<any> = ({ formData, visible, title, onOK, onCancel, form,specs, dispatch }) => {
    const [curCid, setCurCid] = useState(null)
    const [groupIds, setGroupIds] = useState([] as any)
    const [curGroup, setCurGroup] = useState([] as any)
    const [curSKUList, setCurSKUList] = useState([] as any)
    const [groupmap, setGroupmap] = useState({})
    useEffect(() => {
        if (formData && Object.keys(formData).length) {
            setCurType(formData.type);
            setCurCid(formData.cid);
            const imgs = formData.imgs.split(',');
            let fileList:any = [];
            for(const item of imgs) {
                fileList.push({
                    uid: formData.id + Math.random() * 10000,
                    url: item
                } as any)
            }
            setCurFileList(fileList as any)
            setHtmlContent(formData.description || '<h3>请输入</h3>');
            if(formData.groupIds){
              setCurGroup(formData.groupIds.split(','))
            }else {
              setCurGroup([])
            }
            if(formData.skuInfoList){
              setCurSKUList(formData.skuInfoList)
            }else{
              setCurSKUList([])
            }

        }else{
          setCurGroup([])
          setCurSKUList([])
          setHtmlContent( '<h3>请输入</h3>');
        }

        let j = {}
        if(specs){
          for(let i=0;i<specs.length;i++){
            j[specs[i].id] = specs[i]
          }
        }

      setGroupmap(j)

    }, [formData])

    const formItemLayout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 14 },
    }

    const { getFieldDecorator } = form;
    const [loading, setLoading] = useState(false);

    const [curFileList, setCurFileList] = useState([]);

    const uploadSuccess = (file, fileObj) => {
        setLoading(false);
        const { uid, name } = fileObj;
        setCurFileList((curFileList as any).concat([{
            uid,
            name,
            url: curFileUrl,
        }]) as any);

    }

    const handleChange = (info) => { }

    const [curActionUrl, setCurActionUrl] = useState();
    const [curUploadData, setCurUploadData] = useState({});
    const [curFileUrl, setCurUrl] = useState('');
    const beforeUpload = async (file, fileList) => {
        setLoading(true);
        const result = await Service.uploadFileDirect();
        const { host, policy, accessid, signature } = result;
        setCurActionUrl(host);
        const timetamp = new Date().getTime();
        const key = timetamp + '.' + file.name.split('.').pop()
        setCurUrl(host + '/' + key)
        setCurUploadData({
            key,
            policy,
            OSSAccessKeyId: accessid,
            success_action_status: '200',
            signature
        });
        return true;
    }

    const removeSuccess = (file) => {
        let list = [];
        for (const item of curFileList) {
            if ((item as any).uid !== file.uid) list.push(item);
        }
        setCurFileList(list as any);
    }

    /**
     * @desc 文章插图上传配置
     */
    // const uploadInfo = JSON.parse(Cookie.get('upload'));
    // const actionUrl = uploadInfo.host;
    // const data = { ...uploadInfo, host: null }
    // const actionUrl = '';
    const upload: any = {
        name: 'file',
        // action: `${cst.domain}/file/uploadFile`,//上传接口，成功后返回该图片服务器地址
        action: curActionUrl,//上传接口，成功后返回该图片服务器地址
        listType: 'picture-card',
        headers: {
            authorization: 'authorization-text',
        },
        multiple: true,
        onSuccess: uploadSuccess,
        onChange: handleChange,
        beforeUpload: beforeUpload,
        onRemove: removeSuccess,
        data: curUploadData
    }

    /**
     * editor config
     */
    const [curEditorList, setCurEditorList] = useState([])
    const [htmlContent, setHtmlContent] = useState('');

    const receiveHtml = (content: string) => {
        setHtmlContent(content);
        setCurEditorList([]);
    }

    const handleEditorFileChange = (changedValue) => {
        let { file, fileList } = changedValue;
        for (const item of curEditorList) {
            if ((item as any).uid === file.uid) return;
        }
        const { uid, name } = file;
        setCurEditorList(curEditorList.concat([{
            uid,
            name,
            url: curEditorUrl,
        }] as any));
    }

    const [curEditorActionUrl, setCurEditorActionUrl] = useState();
    const [curEditorUploadData, setCurEditorUploadData] = useState({});
    const [curEditorUrl, setCurEditorUrl] = useState('');
    const editorBeforeUpload = async (file, fileList) => {
        const result = await Service.uploadFileDirect();
        const { host, policy, accessid, signature } = result;
        setCurEditorActionUrl(host);
        const timetamp = new Date().getTime();
        const key = timetamp + '.' + file.name.split('.').pop()
        setCurEditorUrl(host + '/' + key)
        setCurEditorUploadData({
            key,
            policy,
            OSSAccessKeyId: accessid,
            success_action_status: '200',
            signature
        });
        return true;
    }

    const removeEditorSuccess = (file) => {
        let list = [];
        for (const item of curEditorList) {
            if ((item as any).uid !== file.uid) list.push(item);
        }
        setCurEditorList(list);
    }

    const editorUpload = {
        action: curEditorActionUrl,
        onChange: handleEditorFileChange,
        listType: 'picture',
        data: curEditorUploadData,
        multiple: false,
        beforeUpload: editorBeforeUpload,
        onRemove: removeEditorSuccess,
    }

    const [curType, setCurType] = useState(null);
    const handleChangeType = value => setCurType(value);


    const addrow = res=>{
      let json = {}
      var skul = [] as any[]
      for(let i=0;i<curGroup.length;i++){
        let temp = {}
        temp['groupId'] = curGroup[i]
        skul.push(temp)
      }
      json['skuInfoList'] = skul
      let arry = [...curSKUList,json]
      setCurSKUList(arry)
    }

    const removeGroup = index =>{
      let arry = curGroup
      arry.splice(index,1)
      setCurGroup([...arry])
      let  arry2 = curSKUList
      for(let i=0;i<arry2.length;i++){
        arry2[i].skuInfoList.splice(index,1)
      }
      setCurSKUList([...arry2])
    }

  const selectGroup = (value)=>{
    if(curGroup.indexOf(value)>-1){
      message.error('此规格已选择')
      return
    }
    var arry = [...curGroup,value]
    setCurGroup(arry)
    let  arry2 = curSKUList
    for(let i=0;i<arry2.length;i++){
      arry2[i].skuInfoList.push({groupId:value})
    }
    setCurSKUList([...arry2])
  }

  const selectop = (index,index2,value)=>{
    let  arry = curSKUList
    arry[index].skuInfoList[index2].valueId = value
    setCurSKUList(arry)
  }

  const selectres= (index,e)=>{
    let  arry = curSKUList
    arry[index].resourceId = e.target.value
    setCurSKUList(arry)
  }
  const selectstock= (index,e)=>{
    let  arry = curSKUList
    arry[index].stock = e.target.value
    setCurSKUList(arry)
  }
  const selectprice= (index,e)=>{
    let  arry = curSKUList
    arry[index].price = e.target.value
    setCurSKUList(arry)
  }



    return (
        <Modal
            visible={visible}
            title={title}
            okText={'保存'}
            cancelText={'取消'}
            onOk={() => {
                setCurFileList([])
                setCurEditorList([])
                onOK && onOK(form, { files: curFileList, description: htmlContent,curGroup,curSKUList })
            }}
            onCancel={() => {
                setCurFileList([])
                setCurEditorList([])
                onCancel(form)
            }}
            width={'65%'}
        >
            <Form.Item {...formItemLayout} label={'商品名称'}>
                {
                    getFieldDecorator('title', {
                        initialValue: formData.title,
                        rules: [{ required: true, message: '请输入商品名称' }],
                    })(<Input className={style.w420} placeholder={'请输入商品名称'} />)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'商品图片'}>
                {
                    getFieldDecorator('imgs', {
                        initialValue: curFileList.length ? curFileList!.map(file => (file as any).url) : '',
                        rules: [{ required: true, message: '请上传商品图片' }],
                        getValueFromEvent: (e) => {
                            return e.fileList
                        }
                    })(<Upload
                        className={style['upload-btn']}
                        {...upload}
                        fileList={curFileList}
                    >
                        <div key={'upload-btn'}>
                            <Icon type={loading ? 'loading' : 'plus'} />
                            <div className='ant-upload-text'>上传</div>
                        </div>
                    </Upload>)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'商品类型'}>
                {
                    getFieldDecorator('type', {
                        initialValue: formData.type,
                        rules: [{ required: true, message: '请选择商品类型' }],
                    })(<Select className={style.w420} placeholder={'请选择商品类型'} onChange={handleChangeType}>
                        <Option key={`option-${1}`} value={0}>实物商品</Option>
                        <Option key={`option-${2}`} value={1}>虚拟商品</Option>
                    </Select>)
                }
            </Form.Item>
            <Form.Item {...formItemLayout} label={'商品类目'}>
                {
                    getFieldDecorator('cid', {
                        initialValue: formData.cid+'',
                        rules: [{ required: true, message: '请选择商品类目' }],
                    })(<Select className={style.w420} placeholder={'请选择商品类目'}>
                        {
                            mapToArray(curType ? FictitiousGoodsType : GoodsType)!.map((column: any, index: number) => <Select.Option key={column.label} value={column.value}>{column.label}</Select.Option>)
                        }
                    </Select>)
                }
            </Form.Item>


             <Form.Item {...formItemLayout} label={'默认价格(元)'}>
                  {
                      getFieldDecorator('price', {
                          initialValue: formData.price,
                          rules: [{ required: true, message: '请输入默认价格' }],
                      })(<Input className={style.w420} placeholder={'请输入默认价格'} />)
                  }
             </Form.Item>
            <Form.Item {...formItemLayout} label={'商品规格'}>
              {
                getFieldDecorator('specs', {
                  initialValue: formData.specs,
                })(
                  <div>
                    新增:<Select className={style.w220} placeholder={'请选择规格'} onChange={selectGroup}>
                      {
                        mapToArray(specs)!.map((column: any, index: number) => <Option key={index} value={column.label.id}>{column.label.groupName}</Option>)
                      }
                    </Select>
                    <div className={style.glist}>
                      {
                        curGroup.map((item:any,index) =>{
                          return (
                            <div key={index} onClick={(e)=>removeGroup(index)}>{groupmap[item].groupName}</div>
                          )
                        })
                      }
                    </div>
                  </div>
                )
              }
            </Form.Item>

            <Form.Item {...formItemLayout} label={'商品SKU'}>
              {
                getFieldDecorator('specs', {
                })(
                  <div>
                    {
                      curSKUList.map((item:any,index) =>{
                        return(
                        <div key={index} className={style.skurow}>
                          <div>商品{index+1}</div>
                          {
                            item.skuInfoList.map((item2:any,index2) =>{
                              return (
                                <div key={index2}>
                                  <div className={style.skus}>
                                    <div className={style.left}>{groupmap[item2.groupId].groupName}</div>
                                    <div className={style.right}>
                                      <Select className={style.w220} placeholder={'请选择'} onChange={e=>selectop(index,index2,e)}  defaultValue={item2.valueId}>
                                        {
                                          mapToArray(groupmap[item2.groupId].propertyNameList)!.map((column: any, index3: number) => <Option key={index3} value={column.label.id}>{column.label.value}</Option>)
                                        }
                                      </Select>
                                    </div>
                                  </div>
                                </div>
                              )
                            })
                          }
                          <div className={style.skus}>
                            <div className={style.left}>资源ID</div>
                            <div className={style.right}><Input className={style.w220} defaultValue={item.resourceId} placeholder={'请输入资源ID'} onChange={e=>selectres(index,e)}/></div>
                          </div>
                          <div className={style.skus}>
                              <div className={style.left}>库存</div>
                              <div className={style.right}><Input className={style.w220} defaultValue={item.stock} placeholder={'请输入库存'} onChange={e=>selectstock(index,e)}/></div>
                          </div>
                          <div className={style.skus}>
                            <div className={style.left}>价格</div>
                            <div className={style.right}><Input className={style.w220} defaultValue={item.price} placeholder={'请输入价格'} onChange={e=>selectprice(index,e)}/></div>
                          </div>

                        </div>
                        )
                      })
                    }
                    <Button type={'primary'} onClick={addrow}>新增</Button>
                  </div>
                )
              }
            </Form.Item>

            <Form.Item label='商品介绍' {...formItemLayout}>
                {getFieldDecorator('description', {
                    // rules: [{ required: true, message: '请编辑内容' }],
                })(
                    <LzEditor
                        active={true}
                        importContent={htmlContent}
                        cbReceiver={receiveHtml}
                        uploadProps={{ ...editorUpload, fileList: curEditorList }}
                        video={false}
                        audio={false}
                        lang={'ch'}
                    />
                )}
            </Form.Item>
        </Modal>
    );
}
const WrappedCreateModal = Form.create<any>({ name: 'modalForm' })(CreateModal);
export default connect((state: any) => {
    return {}
})(WrappedCreateModal);
